package com.service.api.google;




import java.rmi.RemoteException;
import java.util.Map;
import java.util.Map.Entry;

import javax.xml.rpc.ServiceException;

import com.google.api.adwords.lib.AdWordsService;
import com.google.api.adwords.lib.AdWordsServiceLogger;
import com.google.api.adwords.lib.AdWordsUser;
import com.google.api.adwords.lib.utils.MapUtils;
import com.google.api.adwords.v201209.cm.ApiException;
import com.google.api.adwords.v201209.cm.KeywordMatchType;
import com.google.api.adwords.v201209.cm.Language;
import com.google.api.adwords.v201209.cm.Location;
import com.google.api.adwords.v201209.cm.Paging;
import com.google.api.adwords.v201209.o.Attribute;
import com.google.api.adwords.v201209.o.AttributeType;
import com.google.api.adwords.v201209.o.DoubleAttribute;
import com.google.api.adwords.v201209.o.IdeaType;
import com.google.api.adwords.v201209.o.LanguageSearchParameter;
import com.google.api.adwords.v201209.o.LocationSearchParameter;
import com.google.api.adwords.v201209.o.LongAttribute;
import com.google.api.adwords.v201209.o.MonthlySearchVolume;
import com.google.api.adwords.v201209.o.MonthlySearchVolumeAttribute;
import com.google.api.adwords.v201209.o.RelatedToQuerySearchParameter;
import com.google.api.adwords.v201209.o.RequestType;
import com.google.api.adwords.v201209.o.SearchParameter;
import com.google.api.adwords.v201209.o.StringAttribute;
import com.google.api.adwords.v201209.o.TargetingIdea;
import com.google.api.adwords.v201209.o.TargetingIdeaPage;
import com.google.api.adwords.v201209.o.TargetingIdeaSelector;
import com.google.api.adwords.v201209.o.TargetingIdeaServiceInterface;
import com.pub.i.AttributesI;
import com.pub.util.MathUtil;
import com.service.vo.KeywordVo;


public class GetKeywordStats implements AttributesI
{
	
	private AdWordsUser user;
	private TargetingIdeaServiceInterface targetingIdeaService;
	
	public GetKeywordStats(AdWordsUser user)
	{
		 this.user = user;
	}
	
	public GetKeywordStats(String email, String password, String userAgent, String developerToken)
	{
		 user = new AdWordsUser(email, password, userAgent, developerToken);
	}
	
	public void init() throws ServiceException
	{
		targetingIdeaService = user.getService(AdWordsService.V201209.TARGETING_IDEA_SERVICE);
		
		AdWordsServiceLogger.log();
	}
	
	public KeywordVo getStats1(String keywords, KeywordMatchType matchType, int offset, int limit) throws ServiceException, ApiException, RemoteException
	{
		// Log SOAP XML request and response.
	    AdWordsServiceLogger.log();

	    // Create seed keyword.
	    String[] arrKeywords = new String[1];
	    
	    arrKeywords[0] = keywords;
	    
	    // Create selector.
	    TargetingIdeaSelector selector = new TargetingIdeaSelector();
	    selector.setRequestType(RequestType.STATS);
	    selector.setIdeaType(IdeaType.KEYWORD);
	    selector.setRequestedAttributeTypes(new AttributeType[] {
	    		AttributeType.KEYWORD_TEXT, 
	    		AttributeType.COMPETITION, 
	    		AttributeType.TARGETED_MONTHLY_SEARCHES, 
	    		AttributeType.SEARCH_VOLUME
	    	}
	    );

	    // Set selector paging (required for targeting idea service).
	    Paging paging = new Paging();
	    paging.setStartIndex(offset);
	    paging.setNumberResults(limit);
	    selector.setPaging(paging);

	    RelatedToQuerySearchParameter relatedToKeywordSearchParameter = new RelatedToQuerySearchParameter();
	    relatedToKeywordSearchParameter.setQueries(arrKeywords);
 	    selector.setSearchParameters(new SearchParameter[] {relatedToKeywordSearchParameter});

	    // Get related keywords. getBulkKeywordIdeas
	    TargetingIdeaPage page = targetingIdeaService.get(selector);
	    
	    KeywordVo vo = null;
	    
	    TargetingIdea[] targetingIdeas	= page.getEntries();
	    // Display related keywords.
	    if (targetingIdeas != null && targetingIdeas.length > 0) {
	    	vo = new KeywordVo();
	    	
	    	Long globalMonthlySearches;
	    	Long averageMonthlySearches;
	    	 
	    	Map<AttributeType, Attribute> data;
	    	
	    	for (TargetingIdea targetingIdea : targetingIdeas) {
	    		data 	= MapUtils.toMap(targetingIdea.getData());
	    		 
	    		globalMonthlySearches 	= ((LongAttribute) data.get(AttributeType.SEARCH_VOLUME)).getValue();
	    		averageMonthlySearches 	= ((LongAttribute) data.get(AttributeType.TARGETED_MONTHLY_SEARCHES)).getValue();
//TODO 	    is 12 months data		
	    		if(globalMonthlySearches == null)
	    			vo.put(AttributesI.GLOBAL_MONTHLY_SEARCHES, "0");
	    		else
	    			vo.put(AttributesI.GLOBAL_MONTHLY_SEARCHES, globalMonthlySearches.toString());
	    		
	    		if(averageMonthlySearches == null)
	    			vo.put(AttributesI.AVERAGE_MONTHLY_SEARCHES, "0");
	    		else
	    			vo.put(AttributesI.AVERAGE_MONTHLY_SEARCHES, averageMonthlySearches.toString());
	    	}
	    	
    		vo.setKeyword(keywords);
	    }

	    return vo;
	}
	
	public KeywordVo getStats1(KeywordVo vo, KeywordMatchType matchType, int offset, int limit) throws ServiceException, ApiException, RemoteException
	{
		// Log SOAP XML request and response.
	    AdWordsServiceLogger.log();

	    // Create seed keyword.
	    String[] arrKeywords = new String[1];
	    
	    arrKeywords[0] = vo.getKeyword();
	    
	    // Create selector.
	    TargetingIdeaSelector selector = new TargetingIdeaSelector();
	    selector.setRequestType(RequestType.STATS);
	    selector.setIdeaType(IdeaType.KEYWORD);
	    selector.setRequestedAttributeTypes(new AttributeType[] {
	    		AttributeType.KEYWORD_TEXT,
	    		AttributeType.CRITERION, 
	    		AttributeType.SEARCH_VOLUME, 
	    		AttributeType.TARGETED_MONTHLY_SEARCHES
	    	}
	    );

	    // Set selector paging (required for targeting idea service).
	    Paging paging = new Paging();
	    paging.setStartIndex(offset);
	    paging.setNumberResults(limit);
	    selector.setPaging(paging);

	    RelatedToQuerySearchParameter relatedToKeywordSearchParameter = new RelatedToQuerySearchParameter();
	    relatedToKeywordSearchParameter.setQueries(arrKeywords);
 	    selector.setSearchParameters(new SearchParameter[] {relatedToKeywordSearchParameter});

	    // Get related keywords. getBulkKeywordIdeas
	    TargetingIdeaPage page = targetingIdeaService.get(selector);
	    
	    TargetingIdea[] targetingIdeas	= page.getEntries();
	    // Display related keywords.
	    if (targetingIdeas != null && targetingIdeas.length > 0) {
	    	
	    	Long globalMonthlySearches;
	    	Long averageMonthlySearches;
	    	 
	    	Map<AttributeType, Attribute> data;
	    	
	    	for (TargetingIdea targetingIdea : targetingIdeas) {
	    		data 	= MapUtils.toMap(targetingIdea.getData());
	    		 
	    		globalMonthlySearches 	= ((LongAttribute) data.get(AttributeType.SEARCH_VOLUME)).getValue();
	    		averageMonthlySearches 	= ((LongAttribute) data.get(AttributeType.TARGETED_MONTHLY_SEARCHES)).getValue();
	    		
	    		vo.put(AttributesI.GLOBAL_MONTHLY_SEARCHES, globalMonthlySearches.toString());
	    		vo.put(AttributesI.AVERAGE_MONTHLY_SEARCHES, averageMonthlySearches.toString());
	    	}
	    }

	    return vo;
	}
	
	public Map<String, KeywordVo> getStats(Map<String, KeywordVo> keywords, int offset, int limit) throws ServiceException, ApiException, RemoteException
	{
		// Log SOAP XML request and response.
	  

	    // Create seed keyword.
	    int len = keywords.size();
	    
	    String[] arrKeywords = new String[len];
	    StringAttribute keyword;
	    
	    int i = 0;
	    for(Entry<String, KeywordVo> entry: keywords.entrySet()){
		    arrKeywords[i] = entry.getKey();
		    
		    i++;
		}
	
	    // Create selector.
	    TargetingIdeaSelector selector = new TargetingIdeaSelector();
	    selector.setRequestType(RequestType.STATS);
	    selector.setIdeaType(IdeaType.KEYWORD);
	    selector.setRequestedAttributeTypes(new AttributeType[] {
	    		AttributeType.KEYWORD_TEXT, 
	    		AttributeType.COMPETITION, 
	    		AttributeType.SEARCH_VOLUME, AttributeType.TARGETED_MONTHLY_SEARCHES
	    	}
	    );

	    // Set selector paging (required for targeting idea service).
	    Paging paging = new Paging();
	    paging.setStartIndex(offset);
	    paging.setNumberResults(limit);
	    selector.setPaging(paging);

	    RelatedToQuerySearchParameter relatedToKeywordSearchParameter = new RelatedToQuerySearchParameter();
	    relatedToKeywordSearchParameter.setQueries(arrKeywords);
 	    selector.setSearchParameters(new SearchParameter[] {relatedToKeywordSearchParameter});
	    
	    Location unitedStates = new Location();
	    unitedStates.setId(2840L);
	    
	    Language english = new Language();
	    english.setId(1000L);

	    LocationSearchParameter local = new LocationSearchParameter();
	    local.setLocations(new Location[] {unitedStates});
	    
	    LanguageSearchParameter language = new LanguageSearchParameter();
	    language.setLanguages(new Language[] {english});

	    selector.setSearchParameters(new SearchParameter[] {relatedToKeywordSearchParameter, local, language});

	    // Get related keywords. getBulkKeywordIdeas
	    TargetingIdeaPage page = targetingIdeaService.get(selector);
	    
	    TargetingIdea[] targetingIdeas	= page.getEntries();
	    // Display related keywords.
	    if (targetingIdeas != null && targetingIdeas.length > 0) {
	    	Long globalMonthlySearches;
	    	Long averageMonthlySearches;
	    	
	    	Double competition;
	    	MonthlySearchVolume[] targetMonthlySearches;
	    	
	    	KeywordVo vo;
	    	Map<AttributeType, Attribute> data;
	    	
	    	for (TargetingIdea targetingIdea : targetingIdeas) {
	    		data 	= MapUtils.toMap(targetingIdea.getData());
	    		keyword = (StringAttribute) data.get(AttributeType.KEYWORD_TEXT);
	    		
	    		
	    		if(keywords.containsKey(keyword.getValue().toLowerCase())){
	        		vo = keywords.get(keyword.getValue().toLowerCase());
	        		
		    		globalMonthlySearches 	= ((LongAttribute) data.get(AttributeType.SEARCH_VOLUME)).getValue();
 		    		competition 			= ((DoubleAttribute)data.get(AttributeType.COMPETITION)).getValue();
		    		
		    		if(competition == null){
		    			competition = 0D;
		    		}else{
		    			competition =  MathUtil.round(competition, 4);
		    		}
		    		
		    		if(globalMonthlySearches == null){
		    			globalMonthlySearches = 0L;
		    		}
		    		
		    		averageMonthlySearches = 0L;
		    		
		    		
		    		targetMonthlySearches 	= ((MonthlySearchVolumeAttribute) data.get(AttributeType.TARGETED_MONTHLY_SEARCHES)).getValue();
		    		
		    		if(targetMonthlySearches != null){
//		    			vo.put(AttributesI.GLOBAL_MONTHLY_SEARCHES, globalMonthlySearches.toString());
		    			
//		    			System.out.println("==================111===========================");
//		    			
//		    			System.out.println(" tag: " + keyword.getValue()); 
//		    			System.out.println(" length: " + targetMonthlySearches.length);
		    			
		    			
		    			for(i = 0; i < targetMonthlySearches.length; i++){
//		    				System.out.println(" ---year: " + targetMonthlySearches[i].getYear());
//		    				System.out.println(" ---month: " + targetMonthlySearches[i].getMonth());
//		    				System.out.println(" ---count: " + targetMonthlySearches[i].getCount());
		    			
		    				if(targetMonthlySearches[i].getCount() != null)
		    					averageMonthlySearches += targetMonthlySearches[i].getCount();
		    			}
		    			
		    			averageMonthlySearches = averageMonthlySearches / 12L;
		    			
//		    			System.out.println(" globalMonthlySearches: " + globalMonthlySearches); 
//		    			System.out.println(" averageMonthlySearches: " + averageMonthlySearches); 
//		    			System.out.println(" averageMonthlySearches: " + averageMonthlySearches / 12); 
//		    			System.out.println(" competition: " + competition); 
		    		}
		    		
//		    		System.out.println("=============================================");
//		    		System.out.println(" tag: " + keyword.getValue());
//	    			System.out.println(" globalMonthlySearches: " + globalMonthlySearches); 
//	    			System.out.println(" averageMonthlySearches: " + averageMonthlySearches); 
//	    			System.out.println(" competition: " + competition); 

		    		vo.put(AttributesI.GLOBAL_MONTHLY_SEARCHES, globalMonthlySearches);
		    		vo.put(AttributesI.AVERAGE_MONTHLY_SEARCHES, averageMonthlySearches);
		    		vo.put(AttributesI.COMPETITION, competition);		    		
	    		}
	    	}
	    }

	    return keywords;
	}
}
